import json
from socket import MsgFlag

from channels.generic.websocket import WebsocketConsumer
from wxmp.wxmp_utils import ExecJs

from mars.apps.systems.models import WechatConfig
from django.conf import settings

class LogConsumer(WebsocketConsumer):
    # 用于接收上传日志
    def callback(self,msg,type):
        if type == 0:
            self.send(text_data=json.dumps({"code":"200","msg": "{}".format(msg)}))
        elif type == -1 or type == 1:
            self.send(text_data=json.dumps({"code":"999","msg": "{}".format(msg)}))

    def connect(self):
        self.accept()

    def disconnect(self, close_code):
        pass

    def receive(self, text_data):
        # 定义内部函数用于接收上传日志
        def receive_log(text):
            pass
        data_json = json.loads(text_data)
        code = data_json["code"]

        if code == 100:
            # 接收小程序配置id
            ids = str(data_json["msg"])
            # 开始上传小程序
            ids = ids.split(",")
            # 获取小程序配置信息
            wechatConfigs = WechatConfig.objects.filter(id__in=ids)


            for obj in wechatConfigs:
                domain = obj.domain
                if domain.find("https") < 0 and domain.find("http") < 0:
                    domain = "".join(("https://", domain))
                config = {
                    "appid": obj.app_id,
                    "key_path": obj.upload_key,
                    "mp_desc": "",
                    "ver": settings.MP_VER,
                    "host": domain,
                }
                ExecJs.upload(config, self.callback)
                
            


  